<template>
  <view class="wrapper">
    <view class="rightCard">
      <view class="rightCardTop">
        <img
          :src="service.rightCardIcon || service.pic"
          class="rightCardIcon"
        />
        {{ service.name || service.rightName }}
        <view
          class="topTips"
          v-if="
            service &&
            (service.name == '简历诊断' || service.rightName == '简历诊断')
          "
        >
          98%的用户选择
        </view>
      </view>
      <!-- 如果是有报告的情况下需要特殊处理。。 -->
      <template v-if="service && service.rightId == 12">
        <!-- 有多个children，但是只需要显示一个，我服了 -->
        <view class="rightCardBody" @click="handleServiceCardClick(service)">
          <template>
            <view class="left"> </view>
            <view class="right">
              <text>
                {{ service.rightName }}
                {{ service.children.length + '/3' }}</text
              >
              <text class="rightStatusText" v-if="isConsultant">{{
                handleRightstatus(service)
              }}</text>
              <text
                :class="{
                  rightStatusTextBtn: service.rightStatus == 1,
                  rightStatusText: service.rightStatus != 1
                }"
                v-else
                >{{ handleRightBtnstatus(service) }}
                <img :src="arrowRight" alt=""
              /></text>
            </view>
          </template>
        </view>
      </template>
      <!-- 正常情况 -->
      <template v-else>
        <view
          class="rightCardBody"
          v-for="(_item, _index) in service.children"
          :key="_item.rightId"
          @click="handleServiceCardClick(_item)"
        >
          <view class="left">
            <view
              class="up-line"
              :class="[handleUpLineClass(_item, _index, service.children)]"
              v-if="_index != service.children.length + 1"
            >
            </view>
            <view
              class="circle"
              :class="[handleCircleClass(_item, _index, service.children)]"
            >
            </view>
            <view
              class="down-line"
              :class="[handleDownClass(_item, _index, service.children)]"
              v-if="_index != service.children.length - 1"
            >
            </view>
          </view>
          <view class="right">
            <text :class="{ doingRight: _item.rightStatus == 20 }">{{
              _item.rightName
            }}</text>
            <text class="rightStatusText" v-if="isConsultant">{{
              handleRightstatus(_item)
            }}</text>
            <text
              :class="{
                rightStatusTextBtn:
                  (handleRightBtnstatus(_item) == '前往' &&
                    _item.rightStatus == 1) ||
                  handleRightBtnstatus(_item) == '去购买',
                rightStatusText: true
              }"
              v-else
              >{{ handleRightBtnstatus(_item) }} <img :src="arrowRight" alt=""
            /></text>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<script>
import { env } from '@/api/root';
import {
  getPersonRightResult,
  getPersonOneRight,
  getProductGroup,
  getPersonRightNum
} from '@/api/modules/career';
import common from '@/api/common';
export default {
  name: 'zhituServiceCardwithProgress',
  props: {
    service: {
      type: Object,
      default: () => {}
    },
    chatId: {
      type: Object,
      default: ''
    },
    isConsultant: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    service: {
      handler(val) {
        // console.log("service", val);
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getProductGroup();
  },
  data() {
    return {
      projectName: '',
      arrowRight: this.$imgBaseSelf + 'common/arrowRight.png',
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      personName: uni.getStorageSync('person-id') || undefined,
      assessmentVersion: uni.getStorageSync('assessmentVersion'),
      discLeftUseNum: '',
      cardType: ''
    };
  },
  methods: {
    async getProductGroup() {
      const params = {
        personId: uni.getStorageSync('person-id').slice(2) || undefined,
        id: '1'
      };
      const res = await getProductGroup(params);
      if (res.code == 200 && Array.isArray(res.data) && res.data.length) {
        this.projectName = res.data[0].productSign;
      }
    },
    async getPersonRightNumFn(rightId) {
      const params = {
        personId: this.personId || undefined,
        rightId,
        cardType: this.cardType
      };
      const res = await getPersonRightNum(params);
      return res.data.ownNum - res.data.useNum;
    },
    //处理点击卡片里的每一项
    handleServiceCardClick(item) {
      //顾问有一些无法点击，以后可能要改成可以点击
      if (this.isConsultant) return;
      // 同一处理还没开放的情况
      if (item.rightStatus == 0) {
        uni.showToast({ icon: 'none', title: '敬请期待！' });
        return;
      }
      const rightPersonId = this.service.rightPersonId;
      const rightPersonName = this.service.rightPersonName;
      getPersonOneRight({
        rightId: item.rightId,
        personId: rightPersonId
      }).then(async (res) => {
        const nowRightStatus = res.data.rightStatus;
        const childItem = res.data.children ? res.data.children[0] : {};
        this.cardType = res.data.cardType;
        //判断是否购买
        if (nowRightStatus == 4) {
          let rightId = item.rightId;
          //"顾问简历诊断解析"不能购买
          if (rightId == 15) {
            switch (this.projectName) {
              case 'CONSULTE_SERVICE':
                uni.navigateTo({
                  url: `/pagesSub/userCenter/careerPathV2/components/BuyPage`
                });
                break;
              case 'ZHITU_WUHAN_SERVICE':
                uni.navigateTo({
                  url: `/pagesSub/userCenter/careerPathV2/components/WuHanBuyPage`
                });
                break;
              case 'ZHITU_TOC_SERVICE':
                uni.navigateTo({
                  url: `/pagesSub/userCenter/careerPathV2/components/CBuyPage`
                });
                break;
              default:
                break;
            }
            return;
          }
          if (rightId == 17) {
            uni.navigateTo({
              url: `/pagesSub/careerNew/zhituPaytoC/index?rightId=17&cardType=${
                this.cardType || '-1'
              }`
            });
            return;
          }
          if (rightId == 22) {
            switch (this.projectName) {
              case 'CONSULTE_SERVICE':
                uni.navigateTo({
                  url: `/pagesSub/userCenter/careerPathV2/components/BuyPage`
                });
                break;
              case 'ZHITU_WUHAN_SERVICE':
                uni.navigateTo({
                  url: `/pagesSub/userCenter/careerPathV2/components/WuHanBuyPage`
                });
                break;
              case 'ZHITU_TOC_SERVICE':
                uni.navigateTo({
                  url: `/pagesSub/userCenter/careerPathV2/components/CBuyPage`
                });
                break;
              default:
                break;
            }
            // uni.navigateTo({
            //   url: `/pagesSub/userCenter/careerPathV2/components/WuHanBuyPage`,
            // });
          }
        } else if (childItem.rightStatus == 4) {
          let rightId = childItem.rightId;
          //"顾问简历诊断解析"不能购买
          // if (rightId == 15) {
          //   return;
          // }
          switch (this.projectName) {
            case 'CONSULTE_SERVICE':
              uni.navigateTo({
                url: `/pagesSub/userCenter/careerPathV2/components/BuyPage`
              });
              break;
            case 'ZHITU_WUHAN_SERVICE':
              uni.navigateTo({
                url: `/pagesSub/userCenter/careerPathV2/components/WuHanBuyPage`
              });
              break;
            case 'ZHITU_TOC_SERVICE':
              uni.navigateTo({
                url: `/pagesSub/userCenter/careerPathV2/components/CBuyPage`
              });
              break;
            default:
              break;
          }
          return;
        } else if (nowRightStatus == 2) {
          this.openReport(item.extra.fileUrl);
        }

        // 职业测评
        if (item.rightId == 2) {
          if (nowRightStatus == 1) {
            console.log('职业测评还没做');
            uni.navigateTo({
              url: `/pagesSub/career/activity/vocationalAssessment?personId=${rightPersonId}`
            });
          } else {
            uni.navigateTo({
              url: `/pagesSub/careerAssessResultActNew/index?personId=${rightPersonId}`
            });
            // if (!this.assessmentVersion || this.assessmentVersion == '1') {
            //   uni.navigateTo({
            //     url: `/pagesSub/career/activity/CareerAssessResultAct?personId=${rightPersonId}`
            //   });
            // } else if (this.assessmentVersion == '2') {
            //   uni.navigateTo({
            //     url: `/pagesSub/careerAssessResultActNew/index?personId=${rightPersonId}`
            //   });
            // }
          }
        }

        // 职业报告,其实就是职业测评结果页面的职业报告
        if (item.rightId == 9 || item.rightId == 12) {
          //点击职业报告的时候现请求一下是否做完了职业测评
          this.handleCareerReport(2, item);
        }
        if (item.rightId == 3) {
          // 有没有使用过都是跳到完善建立页面
          if (this.isConsultant) return;
          uni.navigateTo({
            url: '/pagesSub/newResume/index'
          });
        }
        //简历诊断
        if (item.rightId == 4) {
          //未使用
          if (nowRightStatus == 1) {
            uni.navigateTo({
              url: '/pagesSub/AIResumeDiagnoseNew/index'
            });
            //已使用
          } else if (nowRightStatus == 2) {
            uni.navigateTo({
              url: `/pagesSub/newResume/resumeAssessment/index?target=AIResumeDiagnoseNew`
            });
          }
        }
        //顾问简历诊断解析
        if (item.rightId == 15) {
          if (nowRightStatus == 1) {
            console.log('请联系顾问进行简历诊断解析');
          } else {
            if (item.extra.fileUrl) {
              this.openReport(item.extra.fileUrl);
            }
          }
        }

        //性格测评
        if (item.rightId == 1) {
          const discLeftUseNum = await this.getPersonRightNumFn();
          //顾问不能点性格测评，webview不能返回聊天页面
          if (this.isConsultant) return;
          if (nowRightStatus == 1) {
            let url;
            if (env == 'test') {
              url = `https://3gtest.crm1001.com/disc/#/disc/question?personId=${rightPersonId}&iname=${rightPersonName}&phone=18825449087&from=careerPathResult&discLeftUseNum=${discLeftUseNum}&cardType=${this.cardType}`;
            } else if (env == 'pro' || env == 'pre') {
              url = `https://3g.crm1001.com/v2/disc/#/disc/question?personId=${rightPersonId}&iname=${rightPersonName}&phone=18825449087&from=careerPathResult&discLeftUseNum=${discLeftUseNum}&cardType=${this.cardType}`;
            }
            uni.navigateTo({
              url:
                '/pagesSub/public/web/descWebView?link=' +
                encodeURIComponent(url)
            });
          }
          if (
            (nowRightStatus == 2 || nowRightStatus == 3) &&
            item.extra &&
            item.extra.userId
          ) {
            let url;
            const userId = item.extra.userId;
            if (env == 'test') {
              url = `https://3gtest.crm1001.com/disc/#/disc/result?userId=${userId}&personId=${this.rightPersonId}&iname=${rightPersonName}&phone=18825449087&from=careerPathResult&cardType=${this.cardType}`;
            } else if (env == 'pro' || env == 'pre') {
              url = `https://3g.crm1001.com/v2/disc/#/disc/result?userId=${userId}&personId=${this.rightPersonId}&iname=${rightPersonName}&phone=18825449087&from=careerPathResult&cardType=${this.cardType}`;
            }
            uni.navigateTo({
              url:
                '/pagesSub/public/web/descWebView?link=' +
                encodeURIComponent(url)
            });
          }
          if (nowRightStatus == 3 && !item.extra) {
            uni.showToast({
              icon: 'none',
              title: '该服务已经过期!',
              duration: 1000
            });
          }
        }
        //ai面试
        if (item.rightId == 17) {
          //点击职业报告的时候现请求一下是否做完了职业测评
          //顾问不能点性格测评，webview不能返回聊天页面
          if (this.isConsultant) return;
          this.handleCareerReport(2, item);
        }
        //职途报告21是第一级，7是第二级
        if (item.rightId == 7) {
          if (item.rightStatus == 1) {
            uni.showToast({
              icon: 'none',
              title: '请咨询顾问生成职途报告！',
              duration: 1000
            });
          } else if (item.rightStatus == 2) {
            const url = item.extra.pdfUrl
              ? item.extra.pdfUrl
              : item.extra.pdfUrlV2;
            this.openReport(url);
          }
        }
      });
    },

    //打开PDF
    openReport(fileUrl) {
      if (!fileUrl) {
        uni.showToast({
          icon: 'none',
          title: '打开职业报告出错！',
          duration: 1000
        });
        return;
      }
      uni.showLoading({
        title: '打开中'
      });

      uni.downloadFile({
        url: fileUrl, // 文件的本身url
        filePath: wx.env.USER_DATA_PATH + '/顾问简历诊断解析' + '.pdf', // 本地自定义的文件名
        success: function (res) {
          let filePath = res.filePath;
          uni.openDocument({
            filePath: filePath,
            success: function () {
              uni.hideLoading();
            },
            fail: function () {
              uni.hideLoading();
            }
          });
          uni.hideLoading();
        },
        fail: function (res) {
          uni.hideLoading();
          uni.showToast({
            icon: 'none',
            title: '链接已经过期！',
            duration: 1000
          });
        },
        complete: (res) => {
          console.log('complete', res);
        }
      });
    },
    //点击职业报告的时候现请求一下是否做完了职业测评
    handleCareerReport(rightId, item) {
      if (item.rightId == 9 || item.rightId == 12) {
        //如果没选择报告的话后端只返回一级 ，但是一级又没有rightCount 所以默认是3
        uni.navigateTo({
          url: `/pagesSub/careerNew/selectCareerReport/index?rightCount=${
            item.rightCount || 3
          }`
        });
      } else if (item.rightId == 17) {
        const queryParams = {
          userNum: item.userNum || 0,
          rightCount: item.rightCount || 3
        };
        const queryString = common.serializeQueryParams(queryParams);
        uni.navigateTo({
          url: `/pagesSub/companyCenter/interviewAI/majorSearchAI${queryString}`
        });
      }
      return;
      //2024年2月2日09:22:03 c端购买这个需求要把职业测评的关联去掉，所以不请求接口了
      getPersonRightResult({
        rightIdList: [rightId],
        personId: this.service.rightPersonId
      }).then((res) => {
        if (res.code == 200) {
          if (res.data.userRightMap[rightId]) {
          } else {
            uni.showToast({ icon: 'none', title: '请先完成职业测评！' });
            return;
          }
        }
      });
    },
    //将rightStatus转化成文字,顾问看显示的
    handleRightstatus(item) {
      //职业报告显示已选择
      // if (_item.rightName.indexOf("报告") != -1) {
      //   return "已完成";
      // }
      switch (item.rightStatus) {
        case 0:
          return '未开放';
        case 1:
          return '未开始';
        case 2:
          return '已完成';
        case 3:
          return '已过期';
        case 4:
          return '未购买';
        default:
          return '未开放';
      }
    },
    //将rightStatus转化成文字2，用户看显示的
    handleRightBtnstatus(item) {
      switch (item.rightStatus) {
        case 0:
          return '未开放';
        case 1:
          if (item.rightId == 15) {
            return '未解答';
          }
          return '前往';
        case 2:
          return '已完成';
        case 3:
          return '已过期';
        case 4:
          return '去购买';
        default:
          return '未开放';
      }
    },
    //处理卡片左边的步骤连线
    handleUpLineClass(item, index, rightsList) {
      const rightStatus = item.rightStatus;
      if (index == 0) return '';
      // 上一个已经完成，而且当前是即将要做的，upLine需高亮
      if (
        (rightsList[index - 1].rightStatus == 2 ||
          rightsList[index - 1].rightStatus == 3) &&
        rightStatus == 1
      ) {
        return 'hasDoneLine';
      } else {
        return 'futureLine';
      }
    },
    //处理卡片左边的步骤连线
    handleDownClass(item, index, rightsList) {
      const rightStatus = item.rightStatus;
      // 当前是第一个，而且是即将要做，无需高亮
      if (index == 0) {
        if (rightStatus == 1) {
          return 'futureLine';
        } else if (rightStatus == 2 || rightStatus == 3) {
          return 'hasDoneLine';
        }
      } else {
        // 如果不是第一个
        if (
          (rightsList[index - 1].rightStatus == 2 ||
            rightsList[index - 1].rightStatus == 3) &&
          rightStatus == 1
        ) {
          return '';
        }
      }
    },
    //处理卡片左边的步骤连线
    handleCircleClass(item, index, rightsList) {
      const rightStatus = item.rightStatus;
      // 如果是第一个，根据状态返回
      if (index == 0) {
        // 如果当前的状态是1而且是第一个，说明即将要进行
        if (rightStatus == 1) {
          return ['goingTodoBg'];
        }
        // 如果当前的状态是2或者3，说明已经完成
        if (rightStatus == 2 || rightStatus == 3) {
          return ['hasDoneBg'];
        }
      } else {
        // 如果是不是第一个
        // 如果当前的状态是2或者3，说明已经完成
        if (rightStatus == 2 || rightStatus == 3) {
          return ['hasDoneBg'];
        }
        // 如果当前的状态是1而且上一个状态是2或者3，说明即将要进行
        if (
          (rightsList[index - 1].rightStatus == 2 ||
            rightsList[index - 1].rightStatus == 3) &&
          rightStatus == 1
        ) {
          return ['goingTodoBg'];
        }
        // 如果上一个状态是1，说明当前的状态是未来要完成的
        if (rightsList[index - 1].rightStatus == 1 && rightStatus == 1) {
          return ['futureTodoBg'];
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.rightCard {
  background: #ffffff;
  border-radius: 16rpx;
  background: linear-gradient(180deg, #fff7ed 0%, #ffffff 40%);
  border-radius: 16rpx;
  padding: 22rpx 22rpx 30rpx;
  width: 515rpx;
  margin: 0 16rpx;

  .rightCardTop {
    display: flex;
    font-size: 32rpx;
    font-family: PingFang-SC, PingFang-SC;
    font-weight: 800;
    color: #333333;
    line-height: 46rpx;
    margin-bottom: 40rpx;

    .rightCardIcon {
      width: 48rpx;
      height: 48rpx;
      margin-right: 18rpx;
    }

    .topTips {
      margin-left: 12rpx;
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
      border: 2rpx solid #ff711e;
      font-size: 24rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #ff7045;
      line-height: 34rpx;
    }
  }

  .rightCardBody {
    display: flex;

    &:last-of-type {
      .right {
        padding-bottom: 0rpx;
      }
    }

    .left {
      display: flex;
      flex-direction: column;

      .up-line {
        height: 15rpx;
        margin-left: 5rpx;
        width: 2rpx;
        background-color: transparent;
      }

      .circle {
        width: 12rpx;
        height: 12rpx;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #d8d8d8;
      }

      .down-line {
        width: 2rpx;
        flex: 1;
        margin-left: 5rpx;
        background-color: #e3e2e2;
      }

      .futureLine {
        background: #e3e2e2;
      }

      .hasDoneLine {
        background: #ffcbbb;
      }

      .hasDoneBg {
        background: #ffcbbb;
      }

      .goingTodoBg {
        background: #ff7045;
      }

      .futureTodoBg {
        background: #d8d8d8;
      }
    }

    .right {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-left: 24rpx;
      padding-bottom: 40rpx;

      text {
        font-size: 28rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #999999;
        line-height: 40rpx;
      }

      .doingRight {
        font-size: 28rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #ff7045;
        line-height: 40rpx;
      }

      .rightStatusText {
        font-size: 26rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #e7a586;
        line-height: 36rpx;
      }

      .rightStatusTextBtn {
        position: relative;
        top: -7rpx;
        color: white;
        padding: 7rpx 24rpx;
        background: #ff711e;
        border-radius: 28rpx;
        border: 3rpx solid #ffffff;

        img {
          width: 9rpx;
          height: 16rpx;
        }
      }
    }
  }
}
</style>
